import {Component, OnInit} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {FilterEnum, FilterTypeEnum} from '../../../core/enum/filter.enum';
import {OtherUtil} from '../../../utils/other.util';
import {SystemPublishService} from './system-publish.service';
import {StatusEnum} from '../../../core/enum/status.enum';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HTTP_BASE_URL, SERVERS_NAME} from '../../../config/config';
import {StorageUtil} from '../../../utils/storage.util';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {SourceServer} from '../../../common/source.server';
import {DatePipe} from '@angular/common';
import {CopyUtil} from '../../../utils/copy.util';

@Component({
  selector: 'app-system-publish',
  templateUrl: './system-publish.component.html',
  styleUrls: ['./system-publish.component.scss'],
  providers: [SystemPublishService, SourceServer, DatePipe]
})
export class SystemPublishComponent implements OnInit {
  pageInfo: PageEntity = new PageEntity();
  tabList = [
    { text: '全部', value: null },
    { text: '待提交', value: 0 },
    { text: '审核中', value: 5 },
    { text: '已发布', value: 10 },
    { text: '未通过', value: 15 },
  ];
  searchParams: SearchParams = new SearchParams();
  targetList = [
    { text: '中干', value: '中干'},
    { text: '老师', value: '老师'},
    { text: '学生', value: '学生'}
  ];
  dataList = [];
  widthConfigs = [
    '60px', '150px', '150px', '150px', '150px',
    '150px', '150px', '150px', '150px', '300px',
    '150px', '150px', '150px', '150px', '150px',
    '250px', '220px'
  ];
  isAllCheck = false;
  isIndeterminate = false;
  canDelete = true;
  mapOfCheckedId = {};
  isView = false;
  formObj: FormObj = new FormObj();
  validateForm: FormGroup;
  pageInfoCase: PageEntity = new PageEntity();
  pageInfoDept: PageEntity = new PageEntity();
  pageInfoMiddle: PageEntity = new PageEntity();
  pageInfoTeacher: PageEntity = new PageEntity();
  pageInfoClass: PageEntity = new PageEntity();
  caseTypeList = [];
  deptTypeList = [];
  deptList = [];
  actionTargetList = [
    { label: '中干', value: '中干', checked: false },
    { label: '老师', value: '老师', checked: false },
    { label: '学生', value: '学生', checked: false },
  ];
  teacherList = [];
  middleList = [];
  classesList = [];
  stateList = [];
  stateObj = {
    0: '新增',
    5: '修订',
    10: '停用'
  };
  publishState = {
    0: '待提交',
    5: '审核中',
    10: '已发布',
    15: '未通过'
  };
  operateAuthList = [
    { label: '查看', value: '查看', checked: false },
    { label: '下载', value: '下载', checked: false },
  ];
  uploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;
  headerInfo = null;
  linkInfo = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}`;
  fileList = [];
  targetMajorListEdit = [];
  targetTeacherListEdit = [];
  targetStudentListEdit = [];
  constructor(
    private http: SystemPublishService,
    private fb: FormBuilder,
    private sourceServer: SourceServer,
    private message: NzMessageService,
    private datePipe: DatePipe
  ) { }

  ngOnInit() {
    this.headerInfo = StorageUtil.getFileHeader();
    this.page(this.pageInfo);
    this.pageInfoCase.filters.type = PaginationUtils.filters('institution-case-type', FilterEnum.CONTAINS);
    this.pageInfoDept.filters.type = PaginationUtils.filters('institution-dept-type', FilterEnum.CONTAINS);
    this.pageInfoCase.rows = 100;
    this.pageInfoDept.rows = 100;
    this.getDictList(this.pageInfoCase, 'case');
    this.getDictList(this.pageInfoDept, 'dept');
    this.getDeptList();
    this.pageInfoTeacher.filters.orgId = PaginationUtils.filters(StorageUtil.getLocalStorage('user').teacher.orgId, FilterEnum.EQUALS);
    this.getTeacherList();
  }

  page(page) {
    this.pageInfo.multiSortMeta = [
      {
        field: 'gmtCreate',
        order: -1
      }
    ];
    this.http.page(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.dataList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
      }
    });
  }

  initForm() {
    this.validateForm = this.fb.group({
      number: [this.formObj.number, [Validators.required]],
      name: [this.formObj.name, [Validators.required]],
      caseType: [this.formObj.caseType, [Validators.required]],
      deptType: [this.formObj.deptType, [Validators.required]],
      deptList: [this.formObj.deptList, [Validators.required]],
      actionTarget: [this.formObj.actionTarget, [Validators.required]],
      targetMajorList: [this.formObj.targetMajorList, []],
      targetTeacherList: [this.formObj.targetTeacherList, []],
      targetStudentList: [this.formObj.targetStudentList, []],
      state: [this.formObj.state, [Validators.required]],
      effectiveDate: [this.formObj.effectiveDate, [Validators.required]],
      viewStartDate: [this.formObj.viewStartDate, []],
      viewEndDate: [this.formObj.viewEndDate, []],
      viewDate: [this.formObj.viewDate, []],
      noLimitViewDate: [this.formObj.noLimitViewDate, []],
      otherDeptAuth: [this.formObj.otherDeptAuth, [Validators.required]],
      sourceIdList: [this.formObj.sourceIdList, []],
      checkerId: [this.formObj.checkerId, [Validators.required]]
    });
  }

  /**
   * 获取字典数据
   */
  getDictList(page, type) {
    this.http.getDictApi(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        if (type === 'case') {
          this.caseTypeList = res.datas.data;
        } else {
          this.deptTypeList = res.datas.data;
        }
      }
    });
  }

  /**
   * 获取部门列表
   */
  getDeptList() {
    this.http.getDeptListApi().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.deptList = res.datas;
      }
    });
  }


  /**
   * 点击查询
   */
  clickSearch() {
    for (const o in this.searchParams) {
      if (this.searchParams[o]) {
        this.pageInfo.filters[o] = PaginationUtils.filters(this.searchParams[o], FilterEnum.CONTAINS);
      } else {
        delete this.pageInfo.filters[o];
      }
    }
    if (this.searchParams.publishState || this.searchParams.publishState === 0) {
      this.pageInfo.filters.publishState = PaginationUtils.filters(this.searchParams.publishState, FilterEnum.EQUALS);
    }
    this.pageInfo.first = 1;
    this.page(this.pageInfo);
  }

  /**
   * 点击新增
   */
  clickAdd() {
    this.isView = true;
    this.formObj = new FormObj();
    this.initForm();
    this.fileList = [];
    this.operateAuthList.map(item => {
      item.checked = false;
    });
    this.actionTargetList.map(item => {
      item.checked = false;
    });
    this.getCurrUserLeader();
    this.targetMajorListEdit = [];
    this.targetTeacherListEdit = [];
    this.targetStudentListEdit = [];
    this.stateList = [
      { label: '新增', value: 0 },
      { label: '修订', value: 5 }
    ];
  }

  /**
   * 获取当前用户的部门领导
   */
  getCurrUserLeader() {
    this.http.getCurrUserLeaderApi().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        if (res.datas && res.datas.leaderId) {
          this.formObj.checkerId = res.datas.leaderId;
        }
      }
    });
  }

  /**
   * 点击编辑
   */
  clickEdit(id) {
    this.http.view(id).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.isView = true;
        this.formObj = new FormObj();
        this.fileList = [];
        this.initForm();
        this.formObj = CopyUtil.deepCopy(res.datas, {});
        this.formObj.deptList = [];
        res.datas.deptList.map(item => {
          this.formObj.deptList.push(item.deptId);
        });
        this.formObj.actionTarget = res.datas.actionTarget.split(',');
        this.actionTargetList.map(item => {
          item.checked = !!this.formObj.actionTarget.includes(item.value);
        });
        this.targetMajorListEdit = [];
        (res.datas.targetMajorList || []).map(item => {
          this.targetMajorListEdit.push(item.targetId);
        });
        this.targetTeacherListEdit = [];
        (res.datas.targetTeacherList || []).map(item => {
          this.targetTeacherListEdit.push(item.targetId);
        });
        this.targetStudentListEdit = [];
        (res.datas.targetStudentList || []).map(item => {
          this.targetStudentListEdit.push(item.targetId);
        });
        this.formObj.effectiveDate = this.datePipe.transform(res.datas.effectiveDate, 'yyyy-MM-dd');
        this.formObj.viewDate = [
          this.datePipe.transform(res.datas.viewStartDate, 'yyyy-MM-dd'),
          this.datePipe.transform(res.datas.viewEndDate, 'yyyy-MM-dd')
        ];
        this.formObj.noLimitViewDate = res.datas.noLimitViewDate === 1;
        this.formObj.otherDeptAuth = res.datas.otherDeptAuth.split(',');
        this.operateAuthList.map(item => {
          item.checked = !!this.formObj.otherDeptAuth.includes(item.value);
        });
        (res.datas.sourceList || []).map(item => {
          this.fileList.push({
            uid: item.id,
            name: item.fileOriginalName,
            status: 'done',
            url: this.linkInfo + 'source/view/' + item.moduleName + '/' + item.fileNewName
          });
        });
        this.stateList = [
          { label: '新增', value: 0 },
          { label: '修订', value: 5 },
          { label: '停用', value: 10 }
        ];
      }
    });
  }

  /**
   * 点击重置
   */
  resetSearch() {
    this.searchParams = new SearchParams();
    this.pageInfo = new PageEntity();
    this.clickSearch();
  }

  searchPageIndex(index) {
    this.pageInfo.first = index;
    this.page(this.pageInfo);
  }

  searchPageSize(size) {
    this.pageInfo.first = 1;
    this.pageInfo.rows = size;
    this.clickSearch();
  }

  /**
   * 点击切换选中tab
   */
  changeTab(data) {
    if (data.value === this.searchParams.publishState) { return false; }
    this.pageInfo = new PageEntity();
    this.searchParams = new SearchParams();
    this.searchParams.publishState = data.value;
    this.clickSearch();
  }

  checkAll(value) {
    this.dataList.forEach(item => this.mapOfCheckedId[item.id] = value);
    this.refreshStatus();
  }
  refreshStatus(): void {
    this.isAllCheck = this.dataList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.dataList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  checkDelete(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  cancelFn() {
    this.canDelete = true;
    this.isAllCheck = false;
    this.mapOfCheckedId = {};
    this.isIndeterminate = false;
  }

  deleteAll() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    if (arr.length < 1) {
      this.message.warning('请勾选要删除的数据!');
      return;
    }
    this.http.deleteAll(arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }

  deleteOne(id) {
    this.http.delete(id).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }

  /**
   * 执行部门改变时
   */
  changeDeptList(value) {
    if (value === undefined || value.length === 0) { return false; }
    this.pageInfoMiddle.filters.type = {
      matchMode: FilterEnum.EQUALS,
      value: 3,
      whereType: FilterTypeEnum.AND
    };
    this.pageInfoMiddle.filters.orgId = {
      matchMode: FilterEnum.IN,
      value: value.join(','),
      whereType: FilterTypeEnum.AND
    };
    this.pageInfoClass.filters.collageId = {
      mathMode: FilterEnum.IN,
      value: value.join(','),
      whereType: FilterTypeEnum.AND
    };
    this.pageInfoMiddle.rows = 100;
    this.pageInfoClass.rows = 100;
    this.formObj.targetMajorList = [];
    this.formObj.targetTeacherList = [];
    this.formObj.targetStudentList = [];
    this.getMiddleList();
    this.getClassList();
  }

  /**
   * 改变作用对象时
   */
  changeActionTarget(value) {
    const arr = [];
    value.map(item => {
      if (item.checked) {
        arr.push(item.value);
      }
    });
    this.formObj.actionTarget = arr;
  }

  /**
   * 改变部门操作权限时
   */
  changeAuth(value) {
    const arr = [];
    value.map(item => {
      if (item.checked) {
        arr.push(item.value);
      }
    });
    this.formObj.otherDeptAuth = arr;
  }

  /**
   * 获取中干列表
   */
  getMiddleList() {
    this.http.getTeacherListApi(this.pageInfoMiddle).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.middleList = res.datas;
        res.datas.map(item => {
          if (this.targetMajorListEdit.includes(item.id)) {
            this.formObj.targetMajorList.push(item.id);
          }
        });
      }
    });
  }

  /**
   * 获取教师列表
   */
  getTeacherList() {
    this.http.getTeacherListApi(this.pageInfoTeacher).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.teacherList = res.datas;
        res.datas.map(item => {
          if (this.targetTeacherListEdit.includes(item.id)) {
            this.formObj.targetTeacherList.push(item.id);
          }
        });
      }
    });
  }

  /**
   * 获取班级列表
   */
  getClassList() {
    this.http.getClassListApi(this.pageInfoClass).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.classesList = res.datas;
        res.datas.map(item => {
          if (this.targetStudentListEdit.includes(item.id)) {
            this.formObj.targetStudentList.push(item.id);
          }
        });
      }
    });
  }

  /**
   * 删除上传资源
   * @param file s
   */
  deleteFlile = (file: UploadFile) => {
    this.fileList.forEach((item, index) => {
      if (item.uid === file.uid) {
        // 调用后台删除图片
        this.fileList.splice(index, 1);
        this.sourceServer.deleteFile([file.uid]).subscribe(res => {
          if (res.status === StatusEnum.SUCCESS) {
            this.message.success('文件删除成功!');
          }
        });
      }
    });
  }

  // 上传附件
  handleChange(event): void {
    const { file, fileList, type} = event;
    if (type === 'success') {
      if (file.response.status === StatusEnum.SUCCESS) {
        fileList.forEach((item) => {
          if (item.response) {
            const datas = item.response.datas;
            item.uid = datas.id;
            item.url = this.linkInfo + 'source/view/' + datas.moduleName + '/' + datas.fileNewName;
          }
        });
        this.fileList = [fileList[fileList.length - 1]];
      } else {
        this.message.warning('文件上传失败,请重新上传!');
        this.fileList = [];
      }
    } else if (type === 'error') {
      this.fileList = [];
    }
  }

  /**
   * 点击暂存
   */
  stageInstitution() {
    if (this.validateForm.valid) {
      const dataObj = this.buildFormData();
      if (!dataObj) { return false; }
      this.http.stageInstitutionApi(dataObj).subscribe(res => {
        if (res.status === StatusEnum.SUCCESS) {
          this.message.success(res.message);
          this.isView = false;
          this.page(this.pageInfo);
        }
      });
    } else {
      this.message.warning('请输入必填项');
    }
  }

  /**
   * 构建提交数据
   */
  buildFormData() {
    this.formObj.effectiveDate = this.datePipe.transform(this.formObj.effectiveDate, 'yyyy-MM-dd');
    if (!this.formObj.noLimitViewDate) {
      this.formObj.viewStartDate = this.datePipe.transform(this.formObj.viewDate[0], 'yyyy-MM-dd');
      this.formObj.viewEndDate = this.datePipe.transform(this.formObj.viewDate[1], 'yyyy-MM-dd');
    }
    const sourceIdList = [];
    this.fileList.map(item => {
      sourceIdList.push(item.uid);
    });
    if (sourceIdList.length === 0) {
      this.message.warning('附件不能为空');
      return false;
    }

    const deptArr = [];
    this.formObj.deptList.map(item => {
      deptArr.push({
        id: '',
        deptId: item
      });
    });

    const majorArr = [];
    const teacherArr = [];
    const studentArr = [];
    (this.formObj.targetMajorList || []).map(item => {
      majorArr.push({
        id: '',
        targetId: item,
        actionTarget: this.formObj.actionTarget.join(',')
      });
    });
    (this.formObj.targetTeacherList || []).map(item => {
      teacherArr.push({
        id: '',
        targetId: item,
        actionTarget: this.formObj.actionTarget.join(',')
      });
    });
    (this.formObj.targetStudentList || []).map(item => {
      studentArr.push({
        id: '',
        targetId: item,
        actionTarget: this.formObj.actionTarget.join(',')
      });
    });
    const obj = {
      id: this.formObj.id,
      number: this.formObj.number,
      name: this.formObj.name,
      caseType: this.formObj.caseType,
      deptType: this.formObj.deptType,
      deptList: deptArr,
      actionTarget: this.formObj.actionTarget.join(','),
      targetMajorList: majorArr,
      targetTeacherList: teacherArr,
      targetStudentList: studentArr,
      state: this.formObj.state,
      effectiveDate: this.formObj.effectiveDate,
      noLimitViewDate: this.formObj.noLimitViewDate ? 1 : 0,
      otherDeptAuth: this.formObj.otherDeptAuth.join(','),
      sourceIdList,
      checkerId: this.formObj.checkerId
    };
    const dateObj = {
      viewStartDate: this.formObj.viewStartDate,
      viewEndDate: this.formObj.viewEndDate,
    };
    return !this.formObj.noLimitViewDate ? {
      ...obj,
      ...dateObj
    } : obj;
  }

  /**
   * 点击确定
   */
  clickConfirm() {
    if (this.validateForm.valid) {
      const dataObj = this.buildFormData();
      if (!dataObj) { return false; }
      if (this.formObj.id) {
        this.http.update(dataObj).subscribe(res => {
          if (res.status === StatusEnum.SUCCESS) {
            this.message.success(res.message);
            this.isView = false;
            this.page(this.pageInfo);
          }
        });
      } else {
        this.http.create(dataObj).subscribe(res => {
          if (res.status === StatusEnum.SUCCESS) {
            this.message.success(res.message);
            this.isView = false;
            this.page(this.pageInfo);
          }
        });
      }
    } else {
      this.message.warning('请输入必填项');
    }
  }

}
class SearchParams {
  publishState: number = null;
  name: string;
  number: string;
  actionTarget: string;
  publishDeptName: string;
}
class FormObj {
  id: string;
  number: string;
  name: string;
  caseType: string;
  deptType: string;
  deptList: any;
  actionTarget: any;
  targetMajorList: any;
  targetTeacherList: any;
  targetStudentList: any;
  state: number;
  effectiveDate: string;
  viewStartDate: string;
  viewEndDate: string;
  viewDate: any;
  noLimitViewDate: boolean;
  otherDeptAuth: any;
  sourceIdList: any;
  checkerId: string;
}
